#include <QDebug>
#include <QVBoxLayout>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlDatabase>
#include <QMenuBar>
#include <QSqlTableModel>

#include "mainui.h"
#include "global.h"
#include "serialbuffer.h"
#include "serialframe.h"
#include "buzzer.h"


MainUI::MainUI(QWidget *parent) :
    QWidget(parent)
{
    resize(800,480);
    widgetStack = new QStackedWidget(this);
    FullModeWindow = new MainWindow(this);
    SimpleModeWindow = new SimpleMainWindow(this);
    widgetStack->addWidget(FullModeWindow);
    widgetStack->addWidget(SimpleModeWindow);
    widgetStack->setCurrentIndex(0);

    dev_serial = new MyUart;
    int fd = dev_serial->getFileDescriptor();
    if( fd != -1 )
    {
        uart_notifier = new QSocketNotifier(fd,QSocketNotifier::Read,this);
        connect( uart_notifier, SIGNAL(activated(int)), this, SLOT(uartDataCame()) );
    }
    app_data_frame = new SerialFrame;
    msg_processor = new MsgProc(this);
    connect( this, SIGNAL(sig_aplDataComing()), msg_processor, SLOT(aplDataCame()) );
    connect( msg_processor, SIGNAL(sig_sendMsg(QByteArray)), this, SLOT(slot_send_frame(QByteArray)) );

    init_node_status();
    create_actions();
    create_status_bar();

    QVBoxLayout *mainlayout = new QVBoxLayout;
    mainlayout->addWidget(menu_bar);
    mainlayout->addWidget(widgetStack);
    mainlayout->addWidget(status_bar);
    setLayout(mainlayout);

    //隐藏标题栏
    setWindowFlags(Qt::FramelessWindowHint);
}

void MainUI::create_actions()
{
    menu_bar = new QMenuBar(this);
    //文件菜单
    import_config_act = new QAction(tr("&导入配置"),this);
    export_config_act = new QAction(tr("&导出配置"),this);
    menu_bar->addAction(import_config_act);
    menu_bar->addAction(export_config_act);
    connect( import_config_act, SIGNAL(triggered()), this,SLOT(import_config()) );
    connect( export_config_act, SIGNAL(triggered()), this,SLOT(export_config()) );

    //设置菜单
    set_graphic_item_act = new QAction(tr("&手控点设置"), this);
    set_permition_act = new QAction(tr("&系统权限设置"), this);
    menu_bar->addAction(set_graphic_item_act);
    menu_bar->addAction(set_permition_act);
    connect(set_graphic_item_act,SIGNAL(triggered()), this, SLOT(set_graphic_item()));
    connect(set_permition_act,SIGNAL(triggered()), this, SLOT(set_permition()));

    //查询菜单
    keyword_search_act = new QAction(tr("&关键字查询"), this);
    region_search_act = new QAction(tr("&区域查询"), this);
    type_search_act = new QAction(tr("&类型查询"), this);
    menu_bar->addAction(keyword_search_act);
    menu_bar->addAction(region_search_act);
    menu_bar->addAction(type_search_act);
    connect(keyword_search_act, SIGNAL(triggered()), this, SLOT(keyWordSearch()));
    connect(region_search_act, SIGNAL(triggered()), this, SLOT(regionSearch()));
    connect(type_search_act, SIGNAL(triggered()), this, SLOT(typeSearch()));

    //模式选择
    mode_change = new QAction(tr("&简化模式"),this);
    exit_act =new QAction(tr("&退出"),this);
    menu_bar->addAction(mode_change);
    menu_bar->addAction(exit_act);
    connect( mode_change, SIGNAL(triggered()), this, SLOT(change_mode()) );
    connect( exit_act,SIGNAL(triggered()), this, SLOT(close()) );

    //上下翻页
    connect(this,SIGNAL(sig_previous()),FullModeWindow,SLOT(goto_previous_page()));
    connect(this,SIGNAL(sig_previous()),SimpleModeWindow,SLOT(s_goto_previous_page()));
    connect(this,SIGNAL(sig_next()),FullModeWindow,SLOT(goto_next_page()));
    connect(this,SIGNAL(sig_next()),SimpleModeWindow,SLOT(s_goto_next_page()));

    //窗口初始化
    connect(this,SIGNAL(sig_init_show()),FullModeWindow,SLOT(create_initial_show()));
    connect(this,SIGNAL(sig_init_show()),SimpleModeWindow,SLOT(create_initial_show()));

//    menu_bar->setStyleSheet("background-color: darkCyan");
}

void MainUI::create_status_bar()
{
    status_bar = new QStatusBar(this);
    previous_page = new QPushButton(QString("上一页"));
    next_page = new QPushButton(QString("下一页"));
    status_bar->addWidget(previous_page);
    status_bar->addWidget(next_page);

    connect(previous_page, SIGNAL(clicked()), this, SLOT(previous_clicked()) );
    connect(next_page, SIGNAL(clicked()), this, SLOT(next_clicked()) );

//    status_bar->setStyleSheet("background-color: magenta");
}


//从盘导入配置文件
void MainUI::import_config()
{
    //权限验证
    //......

    //清除编号记录
    num_allocate.clear_all();

    //先清除原有数据库中的记录
    QSqlTableModel *model = new QSqlTableModel(this);
    model->database().transaction();
    model->setTable(QString("locate_information_table"));
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    if(model->rowCount()>0)
    {
        model->removeRows(0,model->rowCount());
        model->submitAll();
    }

    model->setTable(QString("device_logoinf_table"));
    model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    model->select();
    if(model->rowCount()>0)
    {
        model->removeRows(0,model->rowCount());
        model->submitAll();
    }
    model->database().commit();

    NodeStatus::Instance()->clear();

    //导入新数据
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    for(int i=1; i<=MAX_NUM_GRA_BTN; ++i)
    {
        if(i % 5 == 0)
        {
            query.exec( QString( "insert into locate_information_table values (%1, 'A区', '001栋', '001层', '101房',  '消防水泵阀', 0 )" ) .arg(i) );
        }
        else if(i % 4 == 0)
        {
            query.exec( QString( "insert into locate_information_table values (%1, 'B区', '002栋', '005层', '211房',  '排烟阀' ,0 )" ) .arg(i) );
        }
        else if(i % 3 == 0)
        {
            query.exec( QString( "insert into locate_information_table values (%1, 'A区', '003栋', '002层', '211房',  '消防水泵阀',0 )" ) .arg(i) );
        }
        else if(i % 2 == 0)
        {
            query.exec( QString( "insert into locate_information_table values (%1, 'B区', '004栋', '002层', '311房',  '消防水泵阀' ,0 )" ) .arg(i) );
        }
        else
        {
            query.exec( QString( "insert into locate_information_table values (%1, 'A区', '005栋', '003层', '311房',  '排烟阀', 0  )" ) .arg(i) );
        }
    }

    query.exec( QString( "insert into device_logoinf_table values ( '消防水泵阀' , './image/device_icon/hb.jpg')" ) );
    query.exec( QString( "insert into device_logoinf_table values ( '排烟阀' , './image/device_icon/hb.jpg')" ) );

    int count=0,btn_id=0;
    query.exec(QString("SELECT id FROM locate_information_table"));
    while(query.next())
    {
        count++;
        btn_id = query.value(0).toInt();
        num_allocate.mark_id(btn_id,true);
        NodeStatus::Instance()->add(btn_id,0);
    }
    num_allocate.updata_tail(count,count);
    QSqlDatabase::database().commit();

    //发送窗口初始化信号
    emit sig_init_show();
}

void MainUI::init_node_status()
{
    //清除编号记录
    num_allocate.clear_all();
    // 清除手控点状态记录
    NodeStatus::Instance()->clear();
    QSqlDatabase::database().transaction();
    QSqlQuery query;
    int count=0,btn_id=0;
    query.exec(QString("SELECT id FROM locate_information_table"));
    while(query.next())
    {
        count++;
        btn_id = query.value(0).toInt();
        num_allocate.mark_id(btn_id,true);
        NodeStatus::Instance()->add(btn_id,0);
    }
    num_allocate.updata_tail(count,count);
    QSqlDatabase::database().commit();
}


//导出配置到U盘
void MainUI::export_config()
{

}

void MainUI::set_permition()
{
    Buzzer::Instance()->start_buzzer();
}

void MainUI::set_graphic_item()
{
    gra_item_setting_dlg = new GraphicItemSettingDialog("locate_information_table",this);
    gra_item_setting_dlg->showMaximized();
}

void MainUI::change_mode()
{
    if(SysMode::Instance()->getMode()==SysMode::FULL_MODE)
    {
        widgetStack->setCurrentIndex(SysMode::SIMPLE_MODE);
        mode_change->setText(tr("&完整模式"));
        SysMode::Instance()->setMode(SysMode::SIMPLE_MODE);
    }
    else
    {
        widgetStack->setCurrentIndex(SysMode::FULL_MODE);
        mode_change->setText(tr("&简化模式"));
        SysMode::Instance()->setMode(SysMode::FULL_MODE);
    }
}

void MainUI::previous_clicked()
{
    emit sig_previous();
}


void MainUI::next_clicked()
{
    emit sig_next();
}

void MainUI::keyWordSearch()
{
    keyWordSearchWindow = new KeyWordSearch(this);
    keyWordSearchWindow->showMaximized();
}

void MainUI::regionSearch()
{
    regionSearchWindow = new RegionSearch(this);
    regionSearchWindow->showMaximized();
}

void MainUI::typeSearch()
{
    typeSearchWindow = new TypeSearch(this);
    typeSearchWindow->showMaximized();
}

//更新状态栏
void MainUI::update_status_bar()
{

}

// 接收原始数据流
void MainUI::uartDataCame()
{
    int cnt = dev_serial->readRawData();
    if( cnt > 0 )
    {
        qDebug()<<cnt<<"bytes data read ";
        app_data_frame->extractAPLframe();
        if( aplRecvBuffer::Instance()->getBuffer().isEmpty() == false )
        {
            qDebug()<<"get application layer data";
            emit sig_aplDataComing();
        }
    }
}

// 发送原始数据流
void MainUI::slot_send_frame(QByteArray msg)
{
        app_data_frame->generateDLLframe(msg);
        dev_serial->writeRawData(msg);
        print(msg);
}

void MainUI::order_to_send(int btn_number)
{
    qDebug()<<"data come";
    QByteArray msg;
    msg[0]=btn_number;
    msg[1]=1;
    msg[2]=100;
    msg[3]=2;
    msg[4]=5;
    slot_send_frame(msg);
}


